import { IAppOption } from "../../typings"
import { UserPermission } from "../../typings/types/mine"
import { userProfileAPI } from "../api/index"
import { LitigationVM } from "../subPackages/packageA/litigation/litigationVM"
import { OperationRiskVM } from "../subPackages/packageA/operatingRisk/details/commonDetail/commonDetailVM"

export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}
export const formatDate = (time: string | number, sym = '-') => {
  let date = new Date(time)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return (
    [year, month, day].map(formatNumber).join(sym)
  )
}

export const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}
// 去除日期字符串的时分秒
export function replaceTime(time: any) {
  return time ? time.slice(0, 10) : "-";
}
// 金额格式化
export function formatPrice(price: string | number, sym: string = "") {
  if (!price) {
    return '-'
  }
  return sym + String(price).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
// 金额格式化2
export function formatCurrency(value: any) {
  if (value) {
    if (parseFloat(value) === 0) {
      return "-"
    } else {
      return formatPrice(parseFloat(value).toFixed(2))
    }
  } else {
    return "-"
  }
}
// 债务人金额展示 如果为null 返回-，否则返回 三位金额分隔 且保留两位小数
// 数据单位是元 改为 万元
export const debtorPrice = (price: string) => {
  if (!price) {
    return '-'
  }
  if (parseFloat(price) === 0) {
    return '-'
  }
  return formatPrice((parseFloat(price) / 10000).toFixed(2))
}

export function isValid<T>(value: T | null | undefined): value is T {
  if (value === null || value === undefined) {
    return false
  }
  if (typeof value === 'string') {
    return value.trim() !== '' && value !== 'null'
  }
  if (typeof value === 'number') {
    return !isNaN(value)
  }
  return true
}

export function validStr(value: string | null | undefined, ph: string = '-', extra: string[] = []): string {
  if (isValid(value)) {
    if (extra.length > 0) {
      const tmp = extra.filter(item => item === value)
      if (tmp.length > 0) return ph
    }
    return value
  }
  return ph
}

export function formateMoneyWithUnitW(value: number | null): string {
  if (!value) return '0'
  const million = value / 10000.0
  return million + ''
}
export const formateDigit = (price: number | string | null) => {
  if (price === null || price === undefined) return ''
  let tmp: number | string = 0
  if (typeof price === 'number') {
    if (price === 0) return ''
    tmp = price.toFixed(2)
  }
  if (typeof price === 'string') {
    if (!isValid(price)) return ''
    tmp = Number(price).toFixed(2)
  }
  return String(tmp).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

export namespace zcc {
  export function split(str?: string, flag: string = ','): string[] {
    if (!str) return []
    if (!str?.includes(flag)) return [str]
    return (str ?? '').split(flag)
  }

  export function logout() {
    wx.removeStorageSync('isLogin')
    wx.removeStorageSync('userInfo')
    wx.removeStorageSync('Cookie')
    wx.removeStorageSync('logs')
    wx.removeStorageSync('token')
    wx.removeStorageSync('permissions')
    getApp<IAppOption>().globalData.isLogin = false
  }

  export function goWebpage(weburl: string, title: string) {
    wx.navigateTo({
      url: '/pages/webpage/webpage?title=' + title
      ,
      success: function (res) {
        res.eventChannel.emit('weburl', weburl)
      }
    })
  }

  export function goOperationRiskDetail(id: number, scene: OperationRiskVM.Scene, navtitle: string) {
    wx.navigateTo({
      url: "/subPackages/packageA/operatingRisk/details/commonDetail/commonDetail?id=" + id + '&scene=' + scene + '&navTitle=' + navtitle
    })
  }

  export function goLitigationDetail(id: number | string, scene: LitigationVM.Scene, navtitle: string, localdata: string | undefined = undefined) {
    wx.navigateTo({
      url: "/subPackages/packageA/litigationDetail/litigationDetail?id=" + id + '&scene=' + scene + '&navTitle=' + navtitle + '&localdata=' + localdata
    })
  }

  export function saveUserProfile(content: UserPermission) {

    const app = getApp<IAppOption>()
    app.globalData.userInfo = content.user
    app.globalData.isLogin = true;
    const permissions2 = handlePermission(content.permissions);
    // console.log(permissions2, "permissions2")
    const permissions = permissions2.map((item: any) => item.permission);
    app.globalData.permissions = permissions
    wx.setStorageSync('userInfo', content.user)
    wx.setStorageSync('isLogin', true)
    wx.setStorageSync('permissions', permissions)
    console.log(content, 'saveUserProfile')
  }

  /** 功能权限处理*/
  function handlePermission(permissions: any) {
    let list: any[] = []
    permissions.forEach((item: any) => {
      if (item.children && item.children.length > 0) {
        list = list.concat(item.children)
      } else {
        list.push(item)
      }
    })
    return list
  }

  export function copyToClipboard(content?: string, alertTitle: string = "已复制") {
    if (!content) return
    wx.setClipboardData({
      data: content,
      success: () => {
        wx.showToast({
          title: alertTitle,
          icon: 'success'
        });
      }
    })
  }

  export function callPhone(number?: string) {
    if (!number) return
    wx.makePhoneCall({
      phoneNumber: number,
      fail: (err) => {
        console.log('拨打电话失败', err);
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        });
      }
    });
  }

  interface UserProfileOptions {
    loading?: boolean
    onSuccess?: () => void
    onFinally?: () => void
  }
  export async function getUserProfile(options: UserProfileOptions = { loading: false }) {
    if (options.loading) {
      wx.showLoading({ title: '' })
    }
    try {
      const res = await userProfileAPI();
      if (res.content) {
        const content = res.content
        zcc.saveUserProfile(content)
        //其他操作
        if (options.onSuccess) {
          options.onSuccess()
        }
      }
    } finally {
      if (options.loading) {
        wx.hideLoading()
      }
      if (options.onFinally) {
        options.onFinally()
      }
    }
  }

  interface ScrollNavigationBarOpacityOption {
    initOpacity: number,
    maxOpacity?: number, //def is 1.0
    max?: number,
    scrollTop: number,
    deltaY: number
  }
  export function getNavOpacityWhenScroll(option: ScrollNavigationBarOpacityOption) {

    let opacity = option.initOpacity
    const max = option.max || 135
    const maxOpacity = option.maxOpacity || 1.0
    if (option.scrollTop <= max) {
      if (option.deltaY >= 0 && option.scrollTop < option.deltaY) {
        opacity = 0
      } else {
        opacity = option.scrollTop / max
      }
    } else if (option.scrollTop > max && option.initOpacity !== maxOpacity) {
      opacity = maxOpacity
    }
    return opacity
  }
}

/** 全局权限判断函数 */
export const checkPermission = (permissionRoles: string[]): boolean => {
  if (Array.isArray(permissionRoles) && permissionRoles.length > 0) {
    const roles = getApp().globalData.permissions;
    // console.log(roles, "roles")
    return roles.some((role: string) => permissionRoles.includes(role))
  } else {
    console.error("need roles! Like checkPermission(['admin','editor'])")
    return false
  }
}